package com.basics.common.utils.weixin.accesstoken;

import com.alibaba.fastjson.JSONObject;
import com.basics.common.constant.Constants;
import com.basics.common.utils.http.SSLUtils;
import com.basics.common.utils.weixin.WxConfigConstants;
import com.basics.common.utils.weixin.model.accesstoken.WebAccessToken;
import com.basics.common.utils.weixin.model.user.WeixinUserInfo;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WeixinGetWebAccessTokenUtil {

	private static final Logger LOG = LoggerFactory.getLogger(WeixinGetWebAccessTokenUtil.class);

	private final static String WX_WEB_TOKEN_GET_ACCESS_TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

	private static final String WX_GET_USER_INFO = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

	// 获得授权后，获取用户信息地址（GET）
	private static final String WX_WEB_TOKEN_GET_USERINFO = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

	/**
	 * 通过用户授权后得到的code信息获取WebAccessToken
	 *
	 * @param code:用户同意授权后得到从微信服务器传来的code信息
	 * @return 如果获取成功，则返回WebAccessToken对象；获取失败则返回null
	 */
	public static WebAccessToken getWebAccessToken(String code) {
		return getWebAccessToken(code,Constants.WX_APPID,Constants.WX_SECRET);

	}

	public static WebAccessToken getWebAccessToken(String code,String appid,String appsecret) {

		WebAccessToken webAccessToken = null;

		// 获取WebAccessToken的接口地址
		String url = WX_WEB_TOKEN_GET_ACCESS_TOKEN.replace("APPID", appid)
				.replace("SECRET", appsecret).replace("CODE", code);
		//String url = WeixinConfigUtil.WX_WEB_TOKEN_GET_USERINFO.replace("ACCESS_TOKEN", code).replace("OPENID", code);
		SSLUtils.setSSL();
		CloseableHttpClient httpClient = HttpClients.createDefault();
		url = url.replaceAll(" ", "");
		HttpPost httpPost = new HttpPost(url);

		try {
			CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

			String result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
			LOG.error("获取token结果:{}",result);
			if (!result.contains("errcode")) {
				webAccessToken = JSONObject.toJavaObject(JSONObject.parseObject(result), WebAccessToken.class);


			} else {

				webAccessToken = null;

			}

		} catch (Exception e) {

			LOG.error("获取WebAccessToken错误： " + e);

		}

		return webAccessToken;

	}

	/**
	 * 通过WebAccessToken对象中的openId和webAccesst操作凭证，获取微信用户的基本信息
	 *
	 * @param webAccessToken：包含web操作凭证和用户的openid
	 * @return WeixinUserInfo：包含用户的昵称和openId
	 */
	public static WeixinUserInfo getWeixinUserInfo(WebAccessToken webAccessToken) {

		WeixinUserInfo weixinUserInfo = null;

		String url = WX_WEB_TOKEN_GET_USERINFO
				.replace("ACCESS_TOKEN", webAccessToken.getAccess_token())
				.replace("OPENID", webAccessToken.getOpenid());
		SSLUtils.setSSL();
		CloseableHttpClient httpClient = HttpClients.createDefault();

		HttpGet httpGet = new HttpGet(url);

		try {

			CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

			String result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
			LOG.error("调用微信获取用户信息接口:{}",result);
			if (!result.contains("errcode")) {

				JSONObject userInfoObj = JSONObject.parseObject(result);

				weixinUserInfo = new WeixinUserInfo();
				weixinUserInfo.setNickName(userInfoObj.getString("nickname"));
				weixinUserInfo.setOpenId(userInfoObj.getString("openid"));
				weixinUserInfo.setSex(userInfoObj.getString("sex"));
				weixinUserInfo.setHeadImgUrl(userInfoObj.getString("headimgurl"));
				weixinUserInfo.setCity(userInfoObj.getString("city"));
				weixinUserInfo.setProvince(userInfoObj.getString("province"));
				weixinUserInfo.setPrivilege(userInfoObj.getString("privilege"));
				weixinUserInfo.setCountry(userInfoObj.getString("country"));
				if(userInfoObj.containsKey("unionid")){
					weixinUserInfo.setUnionId(userInfoObj.getString("unionid"));
				}
			} else {

				weixinUserInfo = null;

			}

		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("获取微信用户基本信息错误： " + e);

		}

		return weixinUserInfo;

	}

	/**
	 * 通过WebAccessToken对象中的openId和webAccesst操作凭证，获取微信用户的基本信息
	 * @return WeixinUserInfo：包含用户的昵称和openId
	 */
	public static WeixinUserInfo getWeixinUserInfo(String accessToken,String openId) {

		WeixinUserInfo weixinUserInfo = null;

		String url = WX_GET_USER_INFO
				.replace("ACCESS_TOKEN", accessToken)
				.replace("OPENID", openId);
		SSLUtils.setSSL();
		CloseableHttpClient httpClient = HttpClients.createDefault();

		HttpGet httpGet = new HttpGet(url);

		try {

			CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

			String result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
			if (!result.contains("errcode")) {

				JSONObject userInfoObj = JSONObject.parseObject(result);

				weixinUserInfo = new WeixinUserInfo();
				weixinUserInfo.setNickName(userInfoObj.getString("nickname"));
				weixinUserInfo.setOpenId(userInfoObj.getString("openid"));
				weixinUserInfo.setSex(userInfoObj.getString("sex"));
				weixinUserInfo.setHeadImgUrl(userInfoObj.getString("headimgurl"));
				weixinUserInfo.setCity(userInfoObj.getString("city"));
				weixinUserInfo.setProvince(userInfoObj.getString("province"));
				weixinUserInfo.setPrivilege(userInfoObj.getString("privilege"));
				weixinUserInfo.setCountry(userInfoObj.getString("country"));
				if(userInfoObj.containsKey("unionid")){
					weixinUserInfo.setUnionId(userInfoObj.getString("unionid"));
				}
			} else {

				weixinUserInfo = null;

			}

		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("获取微信用户基本信息错误： " + e);

		}

		return weixinUserInfo;

	}

}
